package com.ftt;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginTest {
    public static void main(String[] args) {
//        login();
        register();
    }

    public static void login() {
        String username = "admin";
        String password = "123456";
        String sql = "select * from tb_manager where name=? and password=?";
        //1、获取连接
        Connection conn = DBUtile.getConnection();
        //2、获取操作对象
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                System.out.println("登陆成功，用户编号为："+ rs.getInt(1));
            }else{
                System.out.println("登录失败");
            }
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //3、关闭资源
        DBUtile.closeResource(conn, ps, rs);
    }

    public static void register() {
        String username = "admin";
        String password = "123456";
        //1、获取数据库连接
        Connection conn = DBUtile.getConnection();
        String sql1 = "select * from tb_manager where name=?";
        PreparedStatement ps1=null;
        ResultSet rs1=null;
        try {
            ps1 = conn.prepareStatement(sql1);
            ps1.setString(1,username);
            rs1 = ps1.executeQuery();
            if(rs1.next()){
                System.out.println("用户名已存在，注册失败");
            }
            else {
                String sql = "INSERT INTO tb_manager (name.password) VALUES (?, ?)";
                //2、获取操作对象
                PreparedStatement ps = null;
                try{
                    ps = conn.prepareStatement(sql);
                    ps.setString(1,username);
                    ps.setString(2,password);
                    int n = ps.executeUpdate();
                    if(n>0){
                        System.out.println("添加成功");
                    }else {
                        System.out.println("添加失败");
                    }
                }catch (SQLException e){
                    throw new RuntimeException(e);
                }
            }
            conn.commit();
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //3、关闭资源
        DBUtile.closeResource(conn, ps1, rs1);
    }

}
